<template>
  <div class="file-item">
    <div class="imageBox">
      <img
        :src="
          imgType.includes(item.type) ? item.url
          : fileTypeKeys.includes(item.type) ? fileTypeIcon[item.type]
            :fileTypeIcon['tongyong']
        "
      >
    </div>
    <div class="text">
      {{ item.fileName }}
    </div>
    <div v-if="isShowDel || isShowDown" class="icon">
      <el-button v-if="isShowDel" icon="el-icon-delete" circle @click="handleDelete(item)" />
      <el-button v-if="isShowDown" icon="el-icon-download" circle @click="handleDownload(item)" />
    </div>
  </div>
</template>

<script>
import file_type_icon from '@/assets/images/file_type_icon/index'
export default {
  props: {
    file: {
      type: Object,
      default: {}
    },
    isShowDel: {
      type: Boolean,
      default: false
    },
    isShowDown: {
      type: Boolean,
      default: false
    },
    isShowImg: {
      type: Array,
      default() {
        ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'svg']
      }
    }
  },
  data() {
    return {
      fileTypeIcon: file_type_icon,
      fileTypeKeys: Object.keys(file_type_icon),
      imgType: ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'svg'],
      item: null
    }
  },
  watch: {
    file: {
      immediate: true,
      handler(file) {
        file.type = file.type || this.getFileType(file.name || file.fileName)
        this.item = file
      }
    }
  },
  methods: {
    handleDelete() {
      this.$emit('onDelete', this.file)
    },
    handleDownload() {
      window.location.href = this.file.url
    },
    getFileType(name) {
      if (typeof name !== 'string') return ''
      const last = name.lastIndexOf('.')
      return last > -1 ? name.slice(last + 1) : ''
    }
  }
}
</script>

<style lang='scss' scoped>
.file-item {
    width: 112px;
    // height: 150px;
    transition: all 0.2s linear;
    cursor: pointer;
    position: relative;
    .imageBox {
      width: 100%;
      text-align: center;
      height: 100px;
      img {
        width: 100px;
        height: 100px;
      }
    }
    .text {
      text-align: center;
      margin-top: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .icon {
      // width: 40px;
      height: 40px;
      width: 100%;
      position: absolute;
      top: 40px;
      text-align: center;
      display: none;
    }
    // &:hover {
    //   background: rgba(0, 0, 0, 0.1);
    //   transition: all 0.2s linear;
    // }
    &:hover .icon {
      display: block;
    }
  }

  .item.clear {
    border: none;
    height: 0;
    overflow: hidden;
    visibility: hidden;
  }
</style>
